package com.example.demo.Service;

import com.example.demo.entity.*;
import com.example.demo.repository.StarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StarService {
    @Autowired
    private StarRepository starRepository;

    //为文章或评论点赞
    public Star save(Star star) {
        if (star.getPost() != null) {
            //检查是否已经收藏该文章
            if (starRepository.existsByPostAndUser(star.getPost(), star.getUser())) {
                throw new IllegalArgumentException("User has already liked this post");
            }
        }
        //如果没有收藏过，保存新收藏
        return starRepository.save(star);
    }

    //取消收藏
    public void deleteById(Long id) {
        starRepository.deleteById(id);
    }

    //获取某篇文章的收藏数
    public Long countStarsByPost(Post post) {
        return starRepository.countByPost(post);
    }

    //检查用户是否已经收藏某篇文章
    public Star hasStaredPost(Post post, User user) {
        if (starRepository.existsByPostAndUser(post, user)) {
            throw new IllegalStateException("You have already liked this post.");
        }

        Star star = new Star();
        star.setPost(post);
        star.setUser(user);
        return starRepository.save(star);
    }

    //取消文章的收藏
    public void unstarPost(Post post, User user) {
        Star star = starRepository.findByPostAndUser(post, user)
                .orElseThrow(() -> new IllegalStateException("Like not found."));
        starRepository.delete(star);
    }
}
